from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import User, Userinfo, Base
from passlib.context import CryptContext

# 数据库配置
DATABASE_URL = "sqlite:///db.sqlite3"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 加密密钥
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")

# 插入数据
def insert_data():
    session = SessionLocal()
    users_data = [
        {"username": "admin", "password": "admin", "userlevel": 0, "name": "超级管理员", "email": "admin@jsj.com"},
        {"username": "chen", "password": "123456", "userlevel": 1, "name": "陈一", "email": "chen@163.com"},
        {"username": "zhangsan", "password": "456789", "userlevel": 2, "name": "张三", "email": "chen@163.com"},
        {"username": "zeng", "password": "abc", "userlevel": 1, "name": "曾老师", "email": "zeng@163.com"}
    ]
    for user_data in users_data:
        user_data['userpass'] = pwd_context.hash(user_data['password'])
        del user_data['password']
        user = User(**user_data)
        session.add(user)
        userinfo = Userinfo(userid=user.id, **{k: v for k, v in user_data.items() if k not in ["username", "userpass", "userlevel"]})
        session.add(userinfo)
    session.commit()

# 调用插入数据函数
insert_data()